package com.zhuangyuan.cloud.data.service;

import com.zhuangyuan.cloud.data.entities.Cate;
import com.zhuangyuan.cloud.data.repository.sqlite.CateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class CateServiceImpl extends ABaseService implements CateService {
    @Autowired
    private CateRepository cateRepository;

    @Override
    public void add(Cate cate) throws Exception {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.DEFAULT))
                .withIgnoreCase();
        Example<Cate> example = Example.of(cate,matcher);
        if(!cateRepository.exists(example)) {
            cateRepository.save(cate);
        }else{
            throw new Exception(String.format("Cate with name:%s is exists.",cate.getName()));
        }
    }

    @Override
    public Cate addImage(String id,String path) throws Exception {
        Optional<Cate> opt = cateRepository.findById(id);
        if(!opt.isPresent()){
            throw new Exception("specified Cate with id "+id + " is not exists.");
        }
        Cate cate = opt.get();
        String imgPaths = cate.getDetailImagePaths();
        if(imgPaths == null)
            imgPaths = "";
        else if(!imgPaths.endsWith(";")){
            imgPaths += ";";
        }
        imgPaths += path;
        cate.setDetailImagePaths(imgPaths);
        cateRepository.save(cate);
        return cate;
    }

    @Override
    protected JpaRepository getRepository() {
        return cateRepository;
    }
}
